package com.weiyi.chat.ui.activity;

import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;

import com.weiyi.chat.R;
import com.weiyi.chat.api.IUserInfo;
import com.weiyi.chat.common.Constant;
import com.weiyi.chat.common.DemoHelper;
import com.weiyi.chat.common.base.BaseActivity;
import com.weiyi.chat.domain.AllUserInfo;
import com.weiyi.chat.presenter.UserInfoPresenter;
import com.weiyi.chat.utils.FileUtil;
import com.weiyi.chat.utils.MyReusouce;
import com.weiyi.chat.utils.PreferenceUtil;
import com.weiyi.chat.utils.ToastUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;


public class UserProfileActivity extends BaseActivity implements IUserInfo.Views {

    private static final int REQUESTCODE_PICK = 1; // 相册选图标记
    private static final int REQUESTCODE_CUTTING = 2; //图片裁剪
    private static final int REQUESTCODE_TAKE = 3; // 相机拍照标记
    @BindView(R.id.iv_back)
    ImageView mBack;
    @BindView(R.id.title)
    RelativeLayout mTitle;
    @BindView(R.id.user_head_avatar)
    ImageView mUserHeadAvatar;
    @BindView(R.id.user_head_headphoto_update)
    ImageView mUserHeadHeadphotoUpdate;
    @BindView(R.id.user_username)
    TextView mUserUsername;
    @BindView(R.id.user_nickname)
    TextView mUserNickname;
    @BindView(R.id.info_intro)
    TextView mInfoIntro;
    @BindView(R.id.user_tel)
    TextView mUserTel;
    @BindView(R.id.ic_right_arrow)
    ImageView mIcRightArrow;
    @BindView(R.id.ic_right_tel)
    ImageView mIcRightTel;
    @BindView(R.id.rl_nickname)
    RelativeLayout mRlNickname;
    @BindView(R.id.rl_tel_layout)
    RelativeLayout mRlTel;
    @BindView(R.id.ll_info_intro)
    LinearLayout mLlInfoIntro;
    @BindView(R.id.btn_send_msg)
    Button mBtnSendMsg;

    private ProgressDialog dialog;
    private String mUserAccount;
    private String mUserNick;
    private boolean mEnableUpdate;
    private UserInfoPresenter mUserInfoPresenter;
    private String mNickString;
    private String mInfoTelStr;
    private String mInfoIntroStr;
    private static final String IMAGE_FILE_NAME = "avatarImage.jpg";// 头像文件名称
    private String mUserId;

    @Override
    protected int getLayoutResId() {
        return R.layout.em_activity_user_profile;
    }

    @Override
    protected void initView() {
        mUserInfoPresenter = new UserInfoPresenter(this);
        Intent intent = getIntent();
//        mUserAccount = intent.getStringExtra("username");
//        mUserNick = intent.getStringExtra("usernick");
        mUserId = intent.getStringExtra("uid");
        mEnableUpdate = intent.getBooleanExtra("setting", false);
        if (mEnableUpdate) {
            mBtnSendMsg.setVisibility(View.GONE);
            mUserHeadHeadphotoUpdate.setVisibility(View.VISIBLE);
            mIcRightArrow.setVisibility(View.VISIBLE);
            mIcRightTel.setVisibility(View.VISIBLE);
            mUserTel.setText(PreferenceUtil.getValue(Constant.SP_INFO_TEL, mAct));
            mInfoIntro.setText(PreferenceUtil.getValue(Constant.SP_INFO_INTRO, mAct));
            Glide.with(UserProfileActivity.this).load(PreferenceUtil.getValue(Constant.SP_USER_AVATAR, mAct)).into(mUserHeadAvatar);

        } else {
            mUserHeadAvatar.setClickable(false);
            mRlNickname.setClickable(false);
            mRlTel.setClickable(false);
            mLlInfoIntro.setClickable(false);
            mUserHeadHeadphotoUpdate.setVisibility(View.GONE);
            mIcRightArrow.setVisibility(View.INVISIBLE);
        }

        mUserInfoPresenter.getUserInfo(mUserId); //获取用户详细信息

//        mUserUsername.setText(mUserAccount);
//        mUserNickname.setText(mUserNick);

//        if (mUserAccount != null) {
//            if (mUserAccount.equals(EMClient.getInstance().getCurrentUser())) {
//                mUserUsername.setText(EMClient.getInstance().getCurrentUser());
//                EaseUserUtils.setUserNick(mUserAccount, mUserNickname);
//                EaseUserUtils.setUserAvatar(this, mUserAccount, mUserHeadAvatar);
//            } else {
//                mUserUsername.setText(mUserAccount);
//                EaseUserUtils.setUserNick(mUserAccount, mUserNickname);
//                EaseUserUtils.setUserAvatar(this, mUserAccount, mUserHeadAvatar);
//                asyncFetchUserInfo(mUserAccount);
//            }
//        }

    }

    @Override
    protected void initData() {

    }


    @OnClick({R.id.user_head_avatar, R.id.rl_nickname, R.id.iv_back, R.id.btn_send_msg, R.id.rl_tel_layout, R.id.ll_info_intro})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_send_msg:

                Intent intent = new Intent(mAct, ChatActivity.class);
                intent.putExtra(Constant.EXTRA_USER_ID, mUserAccount);
                intent.putExtra(Constant.EXTRA_NICK_NAME, mUserNick);
                intent.putExtra(Constant.EXTRA_ID, mUserId);
                startActivity(intent);
                finish();
                break;
            case R.id.user_head_avatar:
                uploadHeadPhoto();
                break;
            case R.id.rl_nickname:
                final EditText editText = new EditText(this);
                new Builder(this).setTitle(R.string.setting_nickname).setIcon(android.R.drawable.ic_dialog_info).setView(editText)
                        .setPositiveButton(R.string.dl_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mNickString = editText.getText().toString();
                                if (TextUtils.isEmpty(mNickString)) {
                                    Toast.makeText(UserProfileActivity.this, getString(R.string.toast_nick_not_isnull), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                mUserInfoPresenter.updataNickName(mNickString,
                                        PreferenceUtil.getValue(Constant.SP_INFO_INTRO, mAct),
                                        PreferenceUtil.getValue(Constant.SP_INFO_TEL, mAct),
                                        PreferenceUtil.getValue(Constant.SP_TOKEN, mAct)); //TODO
//                                updateRemoteNick(nickString);
                            }
                        }).setNegativeButton(R.string.dl_cancel, null).show();
                break;
            case R.id.rl_tel_layout: //设置固话
                final EditText editText1 = new EditText(this);
                editText1.setInputType(InputType.TYPE_CLASS_NUMBER);
                new Builder(this).setTitle(R.string.setting_tel).setIcon(android.R.drawable.ic_dialog_info).setView(editText1)
                        .setPositiveButton(R.string.dl_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mInfoTelStr = editText1.getText().toString();
                                if (TextUtils.isEmpty(mInfoTelStr)) {
                                    Toast.makeText(UserProfileActivity.this, getString(R.string.toast_nick_not_isnull), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                mUserInfoPresenter.updataNickName(PreferenceUtil.getValue(Constant.SP_BUS_OWNER, mAct),
                                        PreferenceUtil.getValue(Constant.SP_INFO_INTRO, mAct),
                                        mInfoTelStr,
                                        PreferenceUtil.getValue(Constant.SP_TOKEN, mAct)); //TODO
//                                updateRemoteNick(nickString);
                            }
                        }).setNegativeButton(R.string.dl_cancel, null).show();
                break;
            case R.id.ll_info_intro: //设置简介
                final EditText editText2 = new EditText(this);
                new Builder(this).setTitle(R.string.setting_intro).setIcon(android.R.drawable.ic_dialog_info).setView(editText2)
                        .setPositiveButton(R.string.dl_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mInfoIntroStr = editText2.getText().toString();
                                if (TextUtils.isEmpty(mInfoIntroStr)) {
                                    Toast.makeText(UserProfileActivity.this, getString(R.string.toast_nick_not_isnull), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                mUserInfoPresenter.updataNickName(PreferenceUtil.getValue(Constant.SP_BUS_OWNER, mAct),
                                        mInfoIntroStr,
                                        PreferenceUtil.getValue(Constant.SP_INFO_TEL, mAct),
                                        PreferenceUtil.getValue(Constant.SP_TOKEN, mAct)); //TODO
//                                updateRemoteNick(nickString);
                            }
                        }).setNegativeButton(R.string.dl_cancel, null).show();
                break;
        }
    }

    public void asyncFetchUserInfo(String username) {
        DemoHelper.getInstance().getUserProfileManager().asyncGetUserInfo(username, new EMValueCallBack<EaseUser>() {

            @Override
            public void onSuccess(EaseUser user) {
                if (user != null) {
                    DemoHelper.getInstance().saveContact(user);
                    if (isFinishing()) {
                        return;
                    }
                    mUserNickname.setText(user.getNick());
                    if (!TextUtils.isEmpty(user.getAvatar())) {
                        Glide.with(UserProfileActivity.this).load(user.getAvatar()).placeholder(R.drawable.em_default_avatar).into(mUserHeadAvatar);
                    } else {
                        Glide.with(UserProfileActivity.this).load(R.drawable.em_default_avatar).into(mUserHeadAvatar);
                    }
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
            }
        });
    }


    private void uploadHeadPhoto() {
        Builder builder = new Builder(this);
        builder.setTitle(R.string.dl_title_upload_photo);
        builder.setItems(new String[]{getString(R.string.dl_msg_take_photo), getString(R.string.dl_msg_local_upload)},
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        switch (which) {
                            case 0:
                                stratCamera();
                                break;
                            case 1:
                                Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
                                pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                startActivityForResult(pickIntent, REQUESTCODE_PICK);
                                break;
                            default:
                                break;
                        }
                    }
                });
        builder.create().show();
    }

    void stratCamera(){
        Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 下面这句指定调用相机拍照后的照片存储的路径
        takeIntent
                .putExtra(MediaStore.EXTRA_OUTPUT, Uri
                        .fromFile(new File(Environment
                                .getExternalStorageDirectory(),
                                IMAGE_FILE_NAME)));
        startActivityForResult(takeIntent, REQUESTCODE_TAKE);
    }

    private void updateRemoteNick(final String nickName) {
        dialog = ProgressDialog.show(this, getString(R.string.dl_update_nick), getString(R.string.dl_waiting));
        new Thread(new Runnable() {

            @Override
            public void run() {
                boolean updatenick = DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(nickName);

                if (UserProfileActivity.this.isFinishing()) {
                    return;
                }
                if (!updatenick) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(UserProfileActivity.this, getString(R.string.toast_updatenick_fail), Toast.LENGTH_SHORT)
                                    .show();
                            dialog.dismiss();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                            Toast.makeText(UserProfileActivity.this, getString(R.string.toast_updatenick_success), Toast.LENGTH_SHORT)
                                    .show();
                            mUserNickname.setText(nickName);
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUESTCODE_PICK: //相册选择
                if (data == null || data.getData() == null) {
                    return;
                }
                startPhotoZoom(data.getData());
                break;
            case REQUESTCODE_CUTTING: //图片裁剪
                if (data != null) {
                    setPicToView(data);
                }
                break;
            case REQUESTCODE_TAKE: //拍照
                File temp = new File(Environment.getExternalStorageDirectory()
                        + "/" + IMAGE_FILE_NAME);
                startPhotoZoom(Uri.fromFile(temp));
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    /**
     * save the picture data
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(getResources(), photo);
            mUserHeadAvatar.setImageDrawable(drawable);
//            uploadUserAvatar(Bitmap2Bytes(photo));
            String urlpath = FileUtil.saveFile(UserProfileActivity.this, "temphead.jpg", photo); //TODO

            mUserInfoPresenter.updataAcvtar(new File(urlpath),
                    PreferenceUtil.getValue(Constant.SP_TOKEN, mAct),
                    PreferenceUtil.getValue(Constant.SP_BUS_ID, mAct));
        }

    }

    private void uploadUserAvatar(final byte[] data) {
        dialog = ProgressDialog.show(this, getString(R.string.dl_update_photo), getString(R.string.dl_waiting));
        new Thread(new Runnable() {

            @Override
            public void run() {
                final String avatarUrl = DemoHelper.getInstance().getUserProfileManager().uploadUserAvatar(data);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        if (avatarUrl != null) {
                            Toast.makeText(UserProfileActivity.this, getString(R.string.toast_updatephoto_success),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(UserProfileActivity.this, getString(R.string.toast_updatephoto_fail),
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });

            }
        }).start();

        dialog.show();
    }


    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    @Override
    public void onUpdataNick() {
        if (!TextUtils.isEmpty(mNickString)){
            PreferenceUtil.setEdit(Constant.SP_BUS_OWNER, mNickString, mAct);
            mUserNickname.setText(mNickString);
            DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(mNickString);
            //此方法传入一个字符串String类型的参数，返回成功或失败的一个Boolean类型的返回值
            EMClient.getInstance().updateCurrentUserNick(mNickString);
            EMClient.getInstance().pushManager().updatePushNickname(mNickString);
            mNickString = "";
        }else if (!TextUtils.isEmpty(mInfoTelStr)){
            mUserTel.setText(mInfoTelStr);
            PreferenceUtil.setEdit(Constant.SP_INFO_TEL, mInfoTelStr, mAct);
            mInfoTelStr = "";
        }else if (!TextUtils.isEmpty(mInfoIntroStr)){
            mInfoIntro.setText(mInfoIntroStr);
            PreferenceUtil.setEdit(Constant.SP_INFO_INTRO, mInfoIntroStr, mAct);
            mInfoIntroStr = "";
        }
        ToastUtil.showTextToast(mAct, "修改成功");
    }

    @Override
    public void onUpdataAvarar(String headurl) {
        Glide.with(UserProfileActivity.this).load(headurl).into(mUserHeadAvatar);
        PreferenceUtil.setEdit(Constant.SP_USER_AVATAR, headurl, mAct);
        ToastUtil.showTextToast(mAct, "修改成功");
    }

    @Override
    public void onGetUserInfoSuccess(AllUserInfo.BodyBean body) {
        if (mUserId.equals(PreferenceUtil.getValue(Constant.SP_BUS_ID, this))){
            mBtnSendMsg.setVisibility(View.GONE);
        }else{
            mBtnSendMsg.setVisibility(View.VISIBLE);
        }

        mUserNick = body.getData().getInfo_name();
        mUserAccount = body.getData().getBus_mobile();

        mUserTel.setText(body.getData().getInfo_tel());
        mInfoIntro.setText(body.getData().getInfo_intro());
        mUserNickname.setText(mUserNick);
        mUserUsername.setText(mUserAccount);
        Glide.with(UserProfileActivity.this).load(MyReusouce.BASE_URL + body.getData().getInfo_avatar_origin()).into(mUserHeadAvatar);
    }

    @Override
    public void showError(String msg) {
        ToastUtil.showTextToast(mAct, msg);
        if (Constant.TOKEN_FIAL.equals(msg)){
            ToastUtil.showTextToast(mAct, "请重新登录");
            PreferenceUtil.clearAll(mAct);
            toLogin();
        }
    }
}
